<template>
  <div>
    <!-- 查询表单 -->
    <div style="padding: 24px; background: #fff; margin-bottom: 20px">
      <a-form-model layout="inline" :model="formInline">
        <a-form-model-item label="年级:">
          <a-select
            v-model="formInline.grade"
            placeholder="请选择年级"
            style="width: 280px"
          >
            <a-select-option
              v-for="(item, index) in gradelist"
              :key="index"
              :value="item"
            >
              {{ item }}年级
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="班级:">
          <a-select
            v-model="formInline.name"
            placeholder="请选择年级"
            style="width: 280px"
          >
            <a-select-option
              v-for="(item, index) in allclasslist"
              :key="index"
              :value="item"
            >
              {{ item }}班
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="find">
            <a-icon type="search" />
            查询
          </a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-button @click="resetForm()">
            <a-icon type="reload" />
            重置
          </a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="link" v-show="showSrech" @click="changShow()">
            展开 <a-icon type="down"
          /></a-button>
          <a-button type="link" v-show="!showSrech" @click="changShow()">
            收起 <a-icon type="up"
          /></a-button>
        </a-form-model-item>
        <br />
        <a-form-model-item label="课程:" v-show="!showSrech">
          <a-input
            v-model="formInline.curriculum"
            autocomplete="off"
            placeholder="请输入课程名"
            style="width: 280px"
          >
          </a-input>
        </a-form-model-item>
        <a-form-model-item label="科任老师:" v-show="!showSrech">
          <a-select
            v-model="formInline.teacher"
            placeholder="请选择教师"
            style="width: 280px"
          >
            <a-select-option
              v-for="(item, index) in allteacherlist"
              :key="index"
              :value="item.name"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="创建时间:" v-show="!showSrech">
          <a-range-picker
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            :placeholder="['开始时间', '结束时间']"
            @change="onTimeChange"
            @ok="onTimeOk"
          />
        </a-form-model-item>
      </a-form-model>
    </div>

    <div style="padding: 24px 24px 35px 24px; background: #fff">
      <!-- 蓝色计数框 -->
      <div style="width: 100%; margin: 10px 0">
        <a-alert :message="'已选择: ' + this.selectNum" type="info" show-icon />
      </div>

      <!-- 新建表单 / 删除 / 导出 按钮 -->
      <div>
        <a-button type="primary" @click="showModal(0)">
          <a-icon type="plus" />
          新建
        </a-button>
        <a-button
          type="primary"
          @click="export2Excel"
          style="margin-left: 10px"
        >
          <a-icon type="vertical-align-bottom" />
          导出
        </a-button>
        <a-popconfirm
          title="你确定要删除吗？"
          ok-text="确定"
          cancel-text="再想想"
          @confirm="delClass"
        >
          <a-button
            type="danger"
            v-show="selectNum > 0"
            style="margin-left: 10px"
          >
            <a-icon type="close" />
            删除
          </a-button>
        </a-popconfirm>
        <a-modal
          :title="title"
          :visible="visible"
          @ok="handleOk(0)"
          @cancel="handleCancel"
        >
          <a-form-model
            ref="ruleForm"
            :model="ruleForm"
            :rules="addRules"
            v-bind="layout"
          >
            <a-form-model-item has-feedback label="年级" prop="grade">
              <a-select
                v-model="ruleForm.grade"
                placeholder="请选择年级"
                style="width: 180px"
                @select="selectedGrade"
                :disabled="disabled"
              >
                <a-select-option
                  v-for="(item, index) in gradelist"
                  :key="index"
                  :value="item"
                >
                  {{ item }}年级
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item has-feedback label="班级" prop="classname">
              <a-radio-group
                button-style="solid"
                v-model="ruleForm.classname"
                style="width: 180px"
                :disabled="disabled"
              >
                <a-radio-button
                  v-for="(item, index) in classnamelist"
                  :key="index"
                  :value="item.id"
                >
                  {{ item.name }}班
                </a-radio-button>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item has-feedback label="课程" prop="curriculum">
              <a-select
                v-model="ruleForm.curriculum"
                placeholder="请选择课程"
                style="width: 180px"
                @select="selectedCurr"
              >
                <a-select-option
                  v-for="(item, index) in curriculumlist"
                  :key="index"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item has-feedback label="科任老师" prop="teacher">
              <a-radio-group v-model="ruleForm.teacher">
                <a-radio
                  v-for="(item, index) in teacherlist"
                  :key="index"
                  :value="item.tno"
                >
                  {{ item.name }}
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item has-feedback label="正整数测试" prop="textarea1">
              <a-textarea
                placeholder="请随意输入"
                auto-size
                v-model="ruleForm.textarea1"
              />
            </a-form-model-item>
            <a-form-model-item has-feedback label="邮箱测试" prop="textarea2">
              <a-textarea
                placeholder="请随意输入"
                auto-size
                v-model="ruleForm.textarea2"
              />
            </a-form-model-item>
            <a-form-model-item has-feedback label="电话测试" prop="textarea3">
              <a-textarea
                placeholder="请随意输入"
                auto-size
                v-model="ruleForm.textarea3"
              />
            </a-form-model-item>
            <a-form-model-item has-feedback label="浮点数测试" prop="textarea4">
              <a-input placeholder="请随意输入" v-model="ruleForm.textarea4" />
            </a-form-model-item>
            <a-form-model-item has-feedback label="密码测试" prop="textarea5">
              <a-input
                v-model="ruleForm.textarea5"
                autocomplete="off"
                placeholder="请随意输入"
              />
            </a-form-model-item>
          </a-form-model>
        </a-modal>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="data"
        :row-selection="rowSelection"
        :rowKey="
          (record, index) => {
            return index;
          }
        "
        :pagination="false"
        @change="onChange"
        :loading="spin"
        :scroll="{ x: 1080, y: 400 }"
      >
        <span slot="grade" slot-scope="grade">{{ grade }} 年级</span>
        <div slot="classname" slot-scope="classname">
          <span style="color: red" v-if="classname == 1"
            >{{ classname }} 班</span
          >
          <span style="color: blue" v-else-if="classname == 2"
            >{{ classname }} 班</span
          >
        </div>
        <template slot="curriculum" slot-scope="curriculum, record">
          <a-button
            type="link"
            slot="curriculum"
            @click="editCurriculum(record)"
          >
            {{ curriculum }}
          </a-button>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button type="link" slot="action" @click="showModal(record)">
            编辑
          </a-button>
        </template>
      </a-table>
      <!-- 分页器 -->
      <div style="margin: 5px 5px">
        <a-pagination
          v-model="current"
          :page-size-options="pageSizeOptions"
          :total="total"
          show-size-changer
          :page-size="pageSize"
          @change="onSizeChange"
          @showSizeChange="onShowSizeChange"
          :show-total="(total) => `总共 ${total} 条数据`"
          style="float: right"
        >
          <template slot="buildOptionText" slot-scope="props">
            <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
            <span v-if="props.value === '50'">全部</span>
          </template>
        </a-pagination>
      </div>
    </div>
    <!-- 课程编辑表单 -->
    <a-modal
      :visible="showEditCurriculum"
      title="修改课程信息"
      @ok="editOk11(e)"
      @cancel="Cencel"
    >
      <a-form-model ref="form" :model="form" v-bind="layout">
        <a-form-model-item has-feedback label="年级" prop="grade">
          <a-input
            v-model="form.grade"
            autocomplete="off"
            placeholder="请输入年级(实例：2)"
          >
          </a-input>
        </a-form-model-item>
        <a-form-model-item has-feedback label="课程名" prop="name">
          <a-input
            v-model="form.name"
            autocomplete="off"
            allow-clear
            placeholder="请输入班级(实例：'语文课')"
          >
          </a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: "#",
    dataIndex: "id",
    key: "id",
    width: "90px",
    fixed: "left",
    // id自增
    customRender: function (text, record, index) {
      return index + 1;
    },
    align: "center",
  },
  {
    title: "科任老师",
    dataIndex: "teacher",
    key: "teacher",
    align: "center",
    width: "120px",
    scopedSlots: { customRender: "teacher" },
  },
  {
    title: "年级",
    dataIndex: "grade",
    key: "grade",
    align: "center",
    width: "120px",
    scopedSlots: { customRender: "grade" },
    sorter: (a, b) => {
      let aGrade = a.grade - 0;
      let bGrade = b.grade - 0;
      return aGrade - bGrade;
    },
    // 支持的排序方式
    // 默认点击排序按钮是：无排序、顺序、倒序、
    sortDirections: ["descend", "ascend", ""],
    // 配置默认是无序
    defaultSortOrder: "",
  },
  {
    title: "班级",
    dataIndex: "aclass",
    key: "aclass",
    align: "center",
    width: "140px",
    scopedSlots: { customRender: "classname" },
  },
  {
    title: "课程",
    dataIndex: "curriculum",
    key: "curriculum",
    align: "center",
    width: "140px",
    scopedSlots: { customRender: "curriculum" },
  },
  {
    title: "号码",
    dataIndex: "phone",
    key: "phone",
    align: "center",
    width: "140px",
    // ellipsis: true,
    scopedSlots: { customRender: "phone" },
  },
  {
    title: "创建时间",
    dataIndex: "create_time",
    key: "create_time",
    align: "center",
    width: "190px",
    // ellipsis: true,
    scopedSlots: { customRender: "time" },
    sorter: (a, b) => {
      let aTime = new Date(a.create_time).getTime();
      let bTime = new Date(b.create_time).getTime();
      return aTime - bTime;
    },
    sortDirections: ["ascend", "descend"],
    defaultSortOrder: "descend",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    width: "140px",
    fixed: "right",
    scopedSlots: { customRender: "action" },
  },
];

import {
  getClassCurr,
  getAllGrade,
  getClassOfGrade,
  getCurrOfGrade,
  getTeacherOfCurr,
  addClassCurr,
  delClassCurr,
  editClassCurr,
  editCurriculum,
  getAllClass,
  getTeachers,
} from "@/utils/api";
import { export2Excel } from "../utils/excel/excel";
export default {
  name: "ClassCurrManage",
  components: {},
  data() {
    let validateTextarea1 = (rule, value, callback) => {
      if (value == "" || value == undefined) {
        callback();
      } else if (!/^[1-9]{1}[0-9]{0,1}$/.test(value)) {
        callback(new Error("该项只能为正整数,且在1-99之间"));
      } else {
        callback();
      }
    };
    let validateTextarea2 = (rule, value, callback) => {
      if (value == "" || value == undefined) {
        callback();
      } else if (
        !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(
          value
        )
      ) {
        callback(new Error("邮箱格式错误"));
      } else {
        callback();
      }
    };
    let validateTextarea3 = (rule, value, callback) => {
      if (value == "" || value == undefined) {
        callback();
      } else if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    let validateTextarea4 = (rule, value, callback) => {
      if (value == "" || value == undefined) {
        callback();
      } else if (!/^(\d+)(\.\d+)?$/.test(value)) {
        callback(new Error("该项必须是浮点数"));
      } else {
        callback();
      }
    };
    let validateTextarea5 = (rule, value, callback) => {
      if (value == "" || value == undefined) {
        callback();
      } else if (
        !/^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$)([^\u4e00-\u9fa5\s]){6,20}$/.test(
          value
        )
      ) {
        callback(
          new Error(
            "请输入6-20位英文字母、数字或者符号（除空格），且字母、数字和标点符号至少包含两种"
          )
        );
      } else {
        callback();
      }
    };
    return {
      formInline: {
        name: "",
        grade: "",
        curriculum: "",
        teacher: "",
        page: "1",
        pageSize: "10",
        startime: "",
        endtime: "",
      },
      ruleForm: {
        id: "",
        classname: "",
        grade: "",
        curriculum: "",
        teacher: "",
        textarea1: "",
        textarea2: "",
        textarea3: "",
        textarea4: "",
        textarea5: "",
      },
      form: {
        id: "",
        name: "",
        grade: "",
      },
      addRules: {
        textarea1: [
          { validator: validateTextarea1, trigger: ["blur", "change"] },
        ],
        textarea2: [
          { validator: validateTextarea2, trigger: ["blur", "change"] },
        ],
        textarea3: [
          { validator: validateTextarea3, trigger: ["blur", "change"] },
        ],
        textarea4: [
          { validator: validateTextarea4, trigger: ["blur", "change"] },
        ],
        textarea5: [
          { validator: validateTextarea5, trigger: ["blur", "change"] },
        ],
        grade: [
          { required: true, message: "年级不能为空!", trigger: ["blur"] },
        ],
        curriculum: [
          { required: true, message: "课程不能为空!", trigger: ["blur"] },
        ],
        teacher: [
          { required: true, message: "科任老师不能为空!", trigger: ["blur"] },
        ],
        classname: [
          { required: true, message: "班级不能为空!", trigger: ["blur"] },
        ],
      },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
      },
      data: [],
      curriculumlist: [],
      teacherlist: [],
      allteacherlist: [],
      gradelist: [],
      classnamelist: [],
      allclasslist: [],
      columns,
      selectNum: 0,
      selectedRowKeys: [],
      visible: false,
      showSrech: true,
      curriculumName: [],
      selectedRow: [],
      editKey: "",
      title: "",
      disabled: false,
      spin: false,
      showEditCurriculum: false,

      pageSizeOptions: ["10", "20", "30", "40", "50"],
      current: 1,
      pageSize: 10,
      total: 0,
    };
  },
  created() {
    // 获取班级信息
    this.find();
    // 获取所有年级
    getAllGrade().then((res) => {
      this.gradelist = res.data;
    });
    // 获取所有班级
    getAllClass().then((res) => {
      this.allclasslist = res.data;
    });
    // 获取所有课程
    // getAllCurr().then((res) => {
    //   this.curriculum = res.data;
    // });
    // 获取所有教师
    getTeachers({}).then((res) => {
      this.allteacherlist = res.data;
    });
  },
  computed: {
    // 多选相关钩子
    rowSelection() {
      const { selectedRowKeys } = this; // selectedRowKeys和取消选中有关，我也看不懂
      return {
        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          this.selectNum = selectedRows.length;
          // 获取选中的数据
          this.selectedRow = selectedRows;
        },
      };
    },
  },

  watch: {
    // 去掉表单验证信息二次打开残留
    visible(val) {
      //监听的是控制模态框显示或影藏开关的布尔值
      // 监视dialog状态（打开、关闭）
      if (!val) {
        try {
          this.$nextTick(() => {
            this.$refs["ruleForm"].clearValidate(); // 关闭后重置表单验证
            this.teacherlist = []; // 关闭表单后清空教师列表
          });
        } catch (e) {
          console.log(e);
        }
      }
    },
  },
  methods: {
    onChange(pagination) {
      this.selectNum = 0;
      this.selectedRowKeys = []; //取消可选
      this.ipagination = pagination;
    },
    // 改变展开状态
    changShow() {
      this.showSrech = !this.showSrech;
    },
    // 查询表单查询
    find(e = true) {
      if (e) this.formInline.page = 1;
      this.spin = true;
      getClassCurr(this.formInline).then((res) => {
        this.$nextTick(() => {
          this.spin = false;
          this.data = res.data.records;
          this.total = res.data.total;
        });
      });
    },
    // 查询表单重置
    resetForm() {
      this.formInline.name = "";
      this.formInline.grade = "";
      this.formInline.curriculum = "";
      this.formInline.teacher = "";
    },
    // 显示关闭弹窗
    showModal(record) {
      if (record != 0) {
        this.title = "修改课程安排";
        let edit = JSON.parse(JSON.stringify(record));
        this.editKey = edit.id;
        this.disabled = true;
        // 给表单赋值
        this.ruleForm.grade = edit.grade;
        this.ruleForm.classname = edit.aclass;
        this.ruleForm.id = edit.id;
        this.selectedGrade(edit.grade);
        this.selectedCurr(edit.curriculum);
        this.visible = true;
      } else {
        this.title = "新建课程安排";
        this.disabled = false;
        this.visible = true;
      }
    },
    // 新建/配置 弹窗 确认 按钮
    handleOk() {
      if (this.editKey != "") {
        // 编辑确认
        this.$refs["ruleForm"].validate((valid) => {
          if (valid) {
            this.visible = false;
            editClassCurr(this.ruleForm).then((res) => {
              if (res.success != false) this.find();
            });
            this.editKey = "";
          }
        });
      } else {
        // 新建确认
        this.$refs["ruleForm"].validate((valid) => {
          if (valid) {
            this.visible = false;
            addClassCurr(this.ruleForm).then((res) => {
              if (res.success != false) this.find();
            });
          }
        });
      }
      this.ruleForm = {};
    },
    // 新建弹窗 取消 按钮
    handleCancel() {
      this.ruleForm = {};
      this.visible = false;
    },
    // 当年级被选择后
    selectedGrade(value) {
      const params = new URLSearchParams();
      params.append("grade", value);
      //获取该年级下的班级
      getClassOfGrade(params).then((res) => {
        this.classnamelist = res.data;
      });
      //获取该年级下的课程
      getCurrOfGrade(params).then((res) => {
        this.curriculumlist = res.data;
      });
    },
    // 当课程被选择后
    selectedCurr(value) {
      const params = new URLSearchParams();
      params.append("curriculum", value);
      //获取有教该课程，或者暂时没有授课的教师
      getTeacherOfCurr(params).then((res) => {
        this.teacherlist = res.data;
      });
    },
    // 删除班级
    delClass() {
      let ids = [];
      this.selectedRow.forEach((element) => {
        ids.push(element.id);
      });
      delClassCurr(ids).then((res) => {
        if (res.data != null) {
          this.$message.success(res.message);
          this.find();
          this.selectNum = 0;
        } else this.$message.warning(res.message);
      });
    },
    // 打开编辑课程信息
    editCurriculum(e) {
      let edit = JSON.parse(JSON.stringify(e));
      this.form.id = edit.classid;
      this.form.name = edit.curriculum;
      this.form.grade = edit.grade;
      this.showEditCurriculum = true;
    },
    // 编辑课程确认
    editOK11(e) {
      // 编辑确认
      console.log(e);
      this.showEditCurriculum = false;
      editCurriculum(this.form).then((res) => {
        this.$nextTick(() => {
          if (res.success != false) this.find();
        });
      });
      // this.$refs["form"].validate((valid) => {
      //   if (valid) {
      //   }
      // });
      this.form = {};
    },
    // 编辑课程取消
    Cencel() {
      this.showEditCurriculum = false;
      this.form = {};
    },
    // 页码回调
    onSizeChange(page, pageSize) {
      this.formInline.page = page;
      this.formInline.pageSize = pageSize;
      this.find(false);
    },
    // 分页函数
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.formInline.page = current;
      this.formInline.pageSize = pageSize;
      this.find(false);
    },
    // 导出Excel
    export2Excel() {
      let _columns = JSON.parse(JSON.stringify(this.columns));
      // 去掉#号
      _columns.splice(0, 1);
      // 去掉最后的“操作”
      _columns.splice(_columns.length - 1, 1);
      if (this.selectedRow)
        export2Excel(_columns, this.selectedRow, "班级课程关系表");
      else export2Excel(_columns, this.data, "班级课程关系表");
    },
    // 改变时间回调
    onTimeChange(value, dateString) {
      console.log("Selected Time: ", value);
      this.formInline.startime = dateString[0];
      this.formInline.endtime = dateString[1];
    },
    // 时间选择确定回调
    onTimeOk(value) {
      console.log("onOk: ", value);
    },
  },
};
</script>
<style>
</style>